<!--
  智慧社区管理系统 - 退款对话框组件
  @author Wu.Liang
  @date 2025-06-26
  @version 3.0 - 根据系统设计调整方案重构，统一支付接口
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="申请退款"
    width="500px"
    :close-on-click-modal="false"
  >
    <div v-if="paymentData" class="refund-form">
      <!-- 支付信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>支付信息</span>
          </div>
        </template>
        
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">
            {{ paymentData.orderNo }}
          </el-descriptions-item>
          <el-descriptions-item label="支付金额">
            <span class="amount">¥{{ paymentData.formattedAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            {{ paymentData.paymentMethodName }}
          </el-descriptions-item>
          <el-descriptions-item label="支付时间">
            {{ formatDateTime(paymentData.paymentTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 退款表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input-number
            v-model="form.refundAmount"
            :min="0.01"
            :max="paymentData.amount"
            :precision="2"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入退款金额"
          />
          <div class="form-tip">
            最大可退款金额：¥{{ paymentData.formattedAmount }}
          </div>
        </el-form-item>

        <el-form-item label="退款原因" prop="refundReason">
          <el-select
            v-model="form.refundReason"
            placeholder="请选择退款原因"
            style="width: 100%"
            @change="handleReasonChange"
          >
            <el-option label="用户主动申请" value="用户主动申请" />
            <el-option label="系统错误" value="系统错误" />
            <el-option label="重复支付" value="重复支付" />
            <el-option label="服务未提供" value="服务未提供" />
            <el-option label="其他原因" value="其他原因" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.refundReason === '其他原因'" label="具体原因" prop="customReason">
          <el-input
            v-model="form.customReason"
            type="textarea"
            :rows="3"
            placeholder="请输入具体退款原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确认退款
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { PaymentVO } from '../types/payment'

// 作者: Wu.Liang

// Props
interface Props {
  modelValue: boolean
  paymentData: PaymentVO | null
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [data: { refundAmount: number; refundReason: string; remark?: string }]
}>()

// 响应式数据
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  refundAmount: 0,
  refundReason: '',
  customReason: '',
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  refundAmount: [
    { required: true, message: '请输入退款金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '退款金额必须大于0', trigger: 'blur' }
  ],
  refundReason: [
    { required: true, message: '请选择退款原因', trigger: 'change' }
  ],
  customReason: [
    { required: true, message: '请输入具体退款原因', trigger: 'blur' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听器
watch(() => props.modelValue, (newVal) => {
  if (newVal && props.paymentData) {
    resetForm()
  }
})

// 方法
const resetForm = () => {
  Object.assign(form, {
    refundAmount: props.paymentData?.amount || 0,
    refundReason: '',
    customReason: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

const handleReasonChange = () => {
  if (form.refundReason !== '其他原因') {
    form.customReason = ''
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const refundReason = form.refundReason === '其他原因' 
      ? form.customReason 
      : form.refundReason
    
    emit('confirm', {
      refundAmount: form.refundAmount,
      refundReason,
      remark: form.remark
    })
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 工具方法
const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}
</script>

<style scoped>
.refund-form {
  max-height: 600px;
  overflow-y: auto;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}

.amount {
  font-weight: 600;
  color: #67c23a;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  text-align: right;
}
</style> 